package com.hod.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.gears.client.database.DatabaseException;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.HistoryListener;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.PopupPanel;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.core.Ext;
import com.gwtext.client.core.Margins;
import com.gwtext.client.core.Position;
import com.gwtext.client.core.RegionPosition;
import com.gwtext.client.widgets.Component;
import com.gwtext.client.widgets.Container;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.QuickTipsConfig;
import com.gwtext.client.widgets.TabPanel;
import com.gwtext.client.widgets.Toolbar;
import com.gwtext.client.widgets.ToolbarButton;
import com.gwtext.client.widgets.ToolbarTextItem;
import com.gwtext.client.widgets.Viewport;
import com.gwtext.client.widgets.Window;
import com.gwtext.client.widgets.WindowMgr;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.event.PanelListenerAdapter;
import com.gwtext.client.widgets.event.TabPanelListenerAdapter;
import com.gwtext.client.widgets.layout.BorderLayout;
import com.gwtext.client.widgets.layout.BorderLayoutData;
import com.gwtext.client.widgets.layout.FitLayout;
import com.gwtext.client.widgets.menu.BaseItem;
import com.gwtext.client.widgets.menu.Item;
import com.gwtext.client.widgets.menu.Menu;
import com.gwtext.client.widgets.menu.event.BaseItemListenerAdapter;
import com.gwtext.client.widgets.tree.TreePanel;
import com.hod.client.backend.orm.client.GearsDataStore;
import com.hod.client.backend.orm.client.GearsQuery;
import com.hod.client.bedtype.BedType;
import com.hod.client.chargedescription.ChargeDescription;
import com.hod.client.client.Client;
import com.hod.client.frontend.ModuleView;
import com.hod.client.frontend.ScreenManager;
import com.hod.client.frontend.ThemeChanger;
import com.hod.client.room.Room;
import com.hod.client.roomtype.RoomType;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class HOD implements EntryPoint, HistoryListener {

    private static PopupPanel messagePanel = new PopupPanel(true);
    private TabPanel centerPanel;
    private ScreenManager screenManager;
    private Menu menu;
    
    public static native void reload() /*-{
    $wnd.location.reload();
   }-*/;
    /*
     * Inicalizacion de valores del sistema para testeo.
     */
    public static void initValuesHOD(){
    	//clients
    	GearsDataStore ds = (GearsDataStore) GWT.create(Client.class);
    	Client c = new Client();
    	for (int i=1;i<10;i++){
    		c.setIdClient(null);
    		c.setName("Name"+i);
    		c.setSurname("Surname"+i);
    		try {
				ds.save(c);
			} catch (DatabaseException e) {
				// TODO Auto-generated catch block			
			}
    		c = new Client();
    	}    	
    	//roomtypes
    	GearsDataStore ds1 = (GearsDataStore) GWT.create(RoomType.class);
    	RoomType rt = new RoomType();
    	rt.setIdRoomType(null);
    	rt.setName("SINGLE");
    	rt.setMaxPax(2);
    	rt.setNumberOfRooms(1);
    	rt.setPrice(10.10);
    	try {
			ds1.save(rt);
		} catch (DatabaseException e) {
			// TODO Auto-generated catch block
		}
		//reservationState
		//GearsDataStore ds3 = (GearsDataStore) GWT.create(ReservationState.class);
    	//ReservationState rs = new ReservationState();    	
    	//rs.setName("CONFIRMED");
    	//rs.setIdReservationState(null);
    	//ReservationState rs2 = new ReservationState();    	
    	//rs2.setName("FINISHED");
    	//rs2.setIdReservationState(null);
    	//try {
		//	ds3.save(rs);
		//	ds3.save(rs2);
		//} catch (DatabaseException e) {
		//	// TODO Auto-generated catch block
		//}		
		//rooms
		GearsDataStore ds2 = (GearsDataStore) GWT.create(Room.class);
    	Room r = new Room();
		
		for (int i=1;i<10;i++){
    		r.setIdRoom(null);
    		r.setNumber(i+"");
    		r.setIdRoomType(1);
    		r.setFloor(1);
    		r.setState("FREE");
    		try {
				ds2.save(r);
			} catch (DatabaseException e) {
				// TODO Auto-generated catch block			
			}
    		r = new Room();
    	}
		//chargeDescription
		//GearsDataStore ds4 = (GearsDataStore) GWT.create(ChargeDescription.class);
		//ChargeDescription cd = new ChargeDescription();
		//cd.setIdChargeDescription(null);
		//cd.setShortDescription("CHOC.MILKA");
		//cd.setLongDescription("Chocolate Milka");
    	//try {
			//ds4.save(cd);
		//} catch (DatabaseException e) {
			// TODO Auto-generated catch block
		//}
		//bedtypes
		GearsDataStore ds5 = (GearsDataStore) GWT.create(BedType.class);
		BedType tc = new BedType();
		tc.setIdBedType(null);
		tc.setDescription("Cama comun");
		
    	try {
			ds5.save(tc);
		} catch (DatabaseException e) {
			// TODO Auto-generated catch block
		}
		
		
		
		
		
		
		
		
		
		
		
		
    }
    
    public void initTestValues(){
    	GearsDataStore ds = (GearsDataStore) (GWT.create(Client.class));
    	GearsQuery q;
		try {
			q = ds.getNamedQuery(Client.FIND_ALL);
			Client[] data = (Client[]) q.execute();
			if (data.length==0) initValuesHOD(); //si no tengo valores dentro de la base de datos la inicializo con los valores de prueba
			//reload();
		} catch (DatabaseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
    }
    
	public void onModuleLoad() {
        //Inicializar los valores por defecto
		initTestValues();
        //create the main panel and assign it a BorderLayout
        Panel mainPanel = new Panel();
        mainPanel.setLayout(new BorderLayout());

        BorderLayoutData northLayoutData = new BorderLayoutData(RegionPosition.NORTH);
        northLayoutData.setSplit(false);

        BorderLayoutData centerLayoutData = new BorderLayoutData(RegionPosition.CENTER);
        centerLayoutData.setMargins(new Margins(5, 0, 5, 5));

        Panel centerPanelWrappper = new Panel();
        centerPanelWrappper.setLayout(new FitLayout());
        centerPanelWrappper.setBorder(false);
        centerPanelWrappper.setBodyBorder(false);

        centerPanel = new TabPanel();
        centerPanel.setBodyBorder(false);
        centerPanel.setEnableTabScroll(true);
        centerPanel.setAutoScroll(true);
        centerPanel.setAutoDestroy(false);
        centerPanel.setActiveTab(0);

        //hide the panel when the tab is closed
        centerPanel.addListener(new TabPanelListenerAdapter() {
            public boolean doBeforeTabChange(TabPanel source, Panel newPanel, Panel oldPanel) {
                WindowMgr.hideAll();
                return true;
            }

            public void onRemove(Container self, Component component) {
                component.hide();
            }

            public void onContextMenu(TabPanel source, Panel tab, EventObject e) {
                showMenu(tab, e);
            }
        });

        centerPanel.setLayoutOnTabChange(true);
        centerPanel.setTitle("Principal");

        screenManager = new HODScreenManager(centerPanel);

        //setup the west regions layout properties
        BorderLayoutData westLayoutData = new BorderLayoutData(RegionPosition.WEST);
        westLayoutData.setMargins(new Margins(5, 5, 0, 5));
        westLayoutData.setCMargins(new Margins(5, 5, 5, 5));
        westLayoutData.setMinSize(155);
        westLayoutData.setMaxSize(350);
        westLayoutData.setSplit(true);

        //create the west panel and add it to the main panel applying the west region layout properties
        Panel westPanel = createWestPanel();
        mainPanel.add(westPanel, westLayoutData);

        final Panel introPanel = new Panel();
        introPanel.setTitle("HOD Gestion Hotelera");
        introPanel.setPaddings(10);
        introPanel.setLayout(new FitLayout());
        final ModuleView showcaseView = new ModuleView(screenManager);
        introPanel.add(showcaseView);

        centerPanel.add(introPanel, centerLayoutData);
        centerPanelWrappper.add(centerPanel);
        mainPanel.add(centerPanelWrappper, centerLayoutData);

        final String initToken = History.getToken();
        if (initToken.length() != 0) {
            mainPanel.addListener(new PanelListenerAdapter() {
                public void onRender(Component component) {
                    onHistoryChanged(initToken);
                }
            });
        }

        Viewport viewport = new Viewport(mainPanel);

        // Add history listener
        History.addHistoryListener(this);
    }

    private Panel createWestPanel() {
        Panel westPanel = new Panel();
        westPanel.setId("side-nav");
        westPanel.setTitle("Opciones");
        westPanel.setLayout(new FitLayout());
        westPanel.setWidth(210);
        westPanel.setCollapsible(true);

        Toolbar toolbar = new Toolbar();

		if(Ext.isFirebug()) {
			ToolbarButton button = new ToolbarButton();
			button.setIconCls("bug-icon");
			QuickTipsConfig qtipsConfig = new QuickTipsConfig();
			qtipsConfig.setText("Firebug can make the demo run slow.");
			qtipsConfig.setWidth(100);
			qtipsConfig.setMaxWidth(100);
			button.setTooltip(qtipsConfig);
			button.addListener(new ButtonListenerAdapter() {
				public void onClick(Button button, EventObject e) {
					Panel fb = new Panel();
					fb.setAutoScroll(true);
					fb.setAutoLoad("firebug.html");
					final Window window = new Window("Firebug");
					window.setIconCls("bug-icon");
					window.setWidth(550);
					window.setHeight(260);
					window.add(fb);
					window.setCloseAction(Window.CLOSE);
					window.show(button.getElement());

				}
			});
			toolbar.addButton(button);
		}
		//toolbar.addFill();
        //toolbar.addItem(new ToolbarTextItem("Select Theme "));
        //toolbar.addSpacer();
        //toolbar.addField(new ThemeChanger());
        westPanel.setTopToolbar(toolbar);
        
        TabPanel tabPanel = new TabPanel();
        tabPanel.setActiveTab(0);
        tabPanel.setDeferredRender(true);
        tabPanel.setTabPosition(Position.BOTTOM);
        /*TreePanel treePanel = screenManager.getTreeNav();

        tabPanel.add(treePanel);*/
        tabPanel.add(screenManager.getAccordionNav());
        westPanel.add(tabPanel);

        return westPanel;
    }

    /**
     * This method is called whenever the application's history changes.
     *
     * @param historyToken the histrory token
     */
    public void onHistoryChanged(String historyToken) {
        screenManager.showScreen(historyToken);
    }

    private void showMenu(final Panel tab, EventObject e) {
        if (menu == null) {
            menu = new Menu();
            Item close = new Item("Close Tab");
            close.setId("close-tab-item");
            close.addListener(new BaseItemListenerAdapter() {
                public void onClick(BaseItem item, EventObject e) {
                    centerPanel.remove(centerPanel.getActiveTab());
                }
            });
            menu.addItem(close);

            Item closeOthers = new Item("Close Other Tabs");
            closeOthers.setId("close-others-item");
            closeOthers.addListener(new BaseItemListenerAdapter() {
                public void onClick(BaseItem item, EventObject e) {
                    Component[] items = centerPanel.getItems();
                    for (int i = 0; i < items.length; i++) {
                        Panel panel = (Panel) items[i];
                        if (panel.isClosable() && !panel.getId().equals(centerPanel.getActiveTab().getId())) {
                            centerPanel.remove(panel);
                        }
                    }
                }
            });
            menu.addItem(closeOthers);
        }

        BaseItem close = menu.getItem("close-tab-item");
        if (!centerPanel.getActiveTab().isClosable()) {
            close.disable();
        } else {
            close.enable();
        }

        BaseItem closeOthers = menu.getItem("close-others-item");
        if (centerPanel.getItems().length == 1) {
            closeOthers.disable();
        } else {
            closeOthers.enable();
        }
        menu.showAt(e.getXY());
    }

    public static void showMessage(String title, String message) {
        messagePanel.setPopupPosition(500, 300);
        messagePanel.setWidget(new HTML(getMessageHtml(title, message)));
        messagePanel.setWidth("300px");
        messagePanel.show();
    }

    private static native String getMessageHtml(String title, String message) /*-{
                                                          return ['<div class="msg">',
                                                                  '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>',
                                                                  '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc"><h3>', title, '</h3>', message, '</div></div></div>',
                                                                  '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>',
                                                                  '</div>'].join('');
                                                      }-*/;





}
